package main

import (
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/alibaba/sentinel-golang/core/flow"
	"log"
	"time"
)

func main() {
	// 务必先进行初始化
	err := sentinel.InitDefault()
	if err != nil {
		log.Fatalf(err.Error())
	}
	// 配置一条限流规则
	_, err = flow.LoadRules([]*flow.Rule{
		{
			Resource:               "some-test", //熔断器规则生效的埋点资源的名称
			TokenCalculateStrategy: flow.Direct, //Direct表示直接使用字段
			//ControlBehavior:        flow.Reject, //Reject表示超过阈值直接拒绝
			ControlBehavior:  flow.Throttling, //匀速通过
			Threshold:        10,              //QPS流控阈值10个
			StatIntervalInMs: 1000,            //QPS时间长度1s
			//WarmUpPeriodSec: 1, //预热的时间长度
		},
	})
	if err != nil {
		log.Fatalf("配置规则出错：", err.Error())
	}
	for i := 0; i < 12; i++ {
		e, b := sentinel.Entry("some-test", sentinel.WithTrafficType(base.Inbound))
		if b != nil {
			fmt.Println("限流了")
		} else {
			fmt.Println("检查通过")
			e.Exit()
		}
		//配合冷启动策略
		time.Sleep(time.Millisecond * 100)
	}
}
